// @ts-nocheck
import React, { useEffect, useState } from "react";
import "./index.less";
import { NavBar, Radio, Checkbox, Space, Form, Toast } from "antd-mobile";
import { Spin } from "antd";
import { useNavigate, useLocation } from "react-router-dom";
import { HandOk } from "@/components";
import { getQuestionnaire, answerSheet } from "../service";

const QuestionnaireSurvey: React.FC = () => {
  const [loaing, setLoaing] = useState(false);
  const [handOk, setHandOk] = useState(false)
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [articleId, setArticleId] = useState("")
  const [user, setUser] = useState<any>("")
  const location = useLocation();
  const [questionnairesData, setQuestionnairesData] = useState<any>({})
  const [questionnairesDataList, setQuestionnairesDataList] = useState<any>([])


  useEffect(() => {
    const id = location?.search?.substring(1)
    setArticleId(id.split("=")?.[1]);
    const users = JSON.parse(
      localStorage.getItem("users") || JSON.stringify({})
    );
    setUser(users)
  }, [location])

  useEffect(() => {
    if (articleId) {
      getQuestionnaire({ villageCode: "511602006004", id: articleId, })
        .then((res) => {
          if (res.code == 200) {
            setQuestionnairesData(res?.data?.questionnaireDetail);
            setQuestionnairesDataList(res?.data?.qusetionDetail)
          }
        })
        .catch((error) => {
          console.log(error);
        });
    }



  }, [articleId])


  const onFinish = async (values) => {
    let answer = Object.entries(values)
    let answerData = []
    answer?.map((item) => {
      if (Array.isArray(item?.[1])) {
        item?.[1]?.map((mulItem) => {
          answerData.push({
            userId: user.user_id || "",
            userName: user.real_name || "",
            userPhone: user.account || "",
            userIdCard: user.idCard || "",
            questionnaireId: articleId,
            id: mulItem,
            questionCode: item?.[0]
          })
        })
      } else {
        answerData.push({
          userId: user.user_id || "",
          userName: user.real_name || "",
          userPhone: user.account || "",
          userIdCard: user.idCard || "",
          questionnaireId: articleId,
          id: item?.[1],
          questionCode: item?.[0]
        })
      }
    })
    let params = {
      answer:answerData
    }
    try {
      const { success, code, data } = await answerSheet(params);
      if (!(code == 200)) {
        Toast.show({
          icon: "fail",
          content: data,
        });
        setLoaing(false);
        return;
      }
      if (code == 200) {
        setLoaing(false);
        Toast.show({
          icon: "success",
          content: "提交成功",
        });
        setHandOk(true)
      }
    } catch (err) {
      console.error(err);
    }
  }

  const RadioBoxFun = function (data: any) {
    return <Radio.Group >
      <Space direction='vertical'>
        {data?.map((optionItem, optionIndex) => {
          return <Radio key={optionIndex} value={optionItem?.key}>{optionItem?.value}</Radio>
        })}
      </Space>
    </Radio.Group>
  }

  const CheckboxFun = function (data: any) {
    return <Checkbox.Group>
      <Space direction='vertical'>
        {data?.map((optionItem, optionIndex) => {
          return <Checkbox key={optionIndex} value={optionItem?.key}>{optionItem?.value}</Checkbox>
        })}
      </Space>
    </Checkbox.Group>
  }

  return (
    handOk ? <HandOk topTitle="提交成功" title="感谢您的参与" navigateUrl={"/intelligentGovernance/communityQuestionnaire"} header='问卷调查'/>
      :
      <Spin tip="提交中..." spinning={loaing}>
        <div className="QuestionnaireSurvey_contarnier">
          <div className="header-bg">
            <NavBar
              onBack={() => navigate("/intelligentGovernance/communityQuestionnaire")}
            >
              <div className="commontitle">问卷调查</div>
            </NavBar>
          </div>
          {questionnairesData?.id ? <div className="QuestionnaireSurvey-content">
            <div className="QuestionnaireSurveyTitle">{questionnairesData?.title}</div>
            <div className="QuestionnaireSurveyImfor">
              <div className="QuestionnaireSurveyImfor-title">问卷描述</div>
              <div className="QuestionnaireSurveyImfor-content">{questionnairesData?.description}</div>
              <div className="QuestionnaireSurveyImfor-title">起止时间</div>
              <div className="QuestionnaireSurveyImfor-content">{questionnairesData?.startTime} 至 {questionnairesData?.endTime}</div>
            </div>
            {questionnairesDataList?.length > 0 ?
              <div className="QuestionnaireSurveyList">
                <Form form={form} onFinish={onFinish}>
                  {questionnairesDataList?.map((item, index) => {
                    return <Form.Item
                      key={index}
                      name={item?.questionCode}
                      label={item?.title}
                      rules={[{ required: true, message: "必填项" }]}
                    >
                      {item?.multiFlag == "0" ? RadioBoxFun(item?.option)
                        : CheckboxFun(item?.option)
                      }
                    </Form.Item>
                  })}
                  <div className="bottomButton"
                    onClick={(e) => {
                      if (!loaing) {
                        e.preventDefault();
                        form.submit();
                      }
                    }}
                  >
                    {loaing ? "提交中" : "提交"}
                  </div>
                </Form>
              </div> : null}

          </div> : null}

        </div >
      </Spin >
  );
};

export default QuestionnaireSurvey;
